#include "StdAfx.h"
#include "ExNode.h"

#include "Matrix4.h"
#include "ExUtilityFunction.h"

#include "3rd_part\xml\TiXmlUtility.h"

ExNode::ExNode( INode* pNode )
	:m_pNode(pNode),m_pParent(NULL),m_strNodeId("")
{
	m_strNodeId = pNode->GetName();
}


ExNode::~ExNode(void)
{
	itrChildrenNode pos = m_Children.begin();
	for( ; pos != m_Children.end(); ++pos )
		delete *pos;
	
	m_Children.clear();
}

void ExNode::AddChildNode( ExNode* pChild )
{
	assert( pChild != NULL );
	itrChildrenNode pos = std::find(m_Children.begin(), m_Children.end(), pChild );
	if( pos != m_Children.end() )
		return;
	m_Children.push_back( pChild );
	pChild->m_pParent = this;
}

void ExNode::RemoveAllChildrenNodes( void )
{
	m_Children.clear();
}

ExNode* ExNode::GetParent( void ) const
{
	return m_pParent;
}

INode* ExNode::GetMaxNode(void) const
{
	return m_pNode;
}

void ExNode::Save( TiXmlNode* pParentSection )
{
	//portal node will be ignored to save;
	BOOL bIsPortal = FALSE;
	m_pNode->GetUserPropBool( "portal", bIsPortal );
	if( bIsPortal )
		return;

	//node
	std::auto_ptr<TiXmlNode> ptrNodeSection ( new TiXmlElement("Node") );

	//identifier
	std::auto_ptr<TiXmlNode> ptrIdentifierSection ( new TiXmlElement("Identifier") );
	ptrIdentifierSection->InsertEndChild(TiXmlText(m_strNodeId));
	ptrNodeSection->InsertEndChild(*ptrIdentifierSection);
	// end identifier

	//transformation
	std::auto_ptr<TiXmlNode> ptrMatrixSection ( new TiXmlElement("Transformation") );
	Matrix3 matNode = m_pNode->GetNodeTM(0);
	matNode = ExUtilityFunction::ApplyUnitScale( matNode );

	Common::Matrix4 matNodeCommon;
	ExUtilityFunction::Convert( matNode, matNodeCommon );

	TiXmlUtility::WriteMatrix( ExUtilityFunction::MaxToDx( matNodeCommon ), ptrMatrixSection.get() );
	ptrNodeSection->InsertEndChild( *ptrMatrixSection );
	// end transformation

	itrChildrenNode pos = m_Children.begin(); 
	for(; pos != m_Children.end(); ++pos )
		(*pos)->Save( ptrNodeSection.get() );

	// end node
	pParentSection->InsertEndChild( *ptrNodeSection.release() );
}
